package com.xtjc03.serial.domain;

import cn.hutool.core.util.CharsetUtil;
import com.xtjc03.serial.codec.ComMsgProtocolFactory;
import com.xtjc03.serial.handler.ComMsgHandler;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.transport.serial.SerialAddress;
import org.apache.mina.transport.serial.SerialConnector;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.nio.charset.Charset;

@Component
public class MySerialPort implements CommandLineRunner {

    @Autowired
    ComProperties comProperties;

    private IoSession ioSession;

    public IoSession getIoSession() {
        return ioSession;
    }

    public void init(){
        IoConnector serialConnector = new SerialConnector();
        serialConnector.getFilterChain().addLast("filter1", new ProtocolCodecFilter(new ComMsgProtocolFactory()));
        serialConnector.setHandler(new ComMsgHandler());

        SerialAddress serialAddress = new SerialAddress(comProperties.getName(),
                comProperties.getBauds(),
                comProperties.getDataBits(),
                comProperties.getStopBits(),
                comProperties.getParity(),
                comProperties.getFlowControl());
        System.out.println(comProperties);
        ConnectFuture connect = serialConnector.connect(serialAddress);
        try {
            connect.await();
            String properties = comProperties.getName() + ","
                    + comProperties.getBauds() + ","
                    + comProperties.getDataBits().toString() + ","
                    + comProperties.getStopBits().toString() + ","
                    + comProperties.getParity().toString() + ","
                    + comProperties.getFlowControl().toString() + "\r\n";
            this.ioSession = connect.getSession();
            this.ioSession.write(properties);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run(String... args) throws Exception {
        this.init();
    }
}
